package com.xmmxjy.config;

import com.xiaoleilu.hutool.date.DateUtil;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Date;

/**
 * 自定义精确分片算法
 * @author xmm
 */
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

	private Logger logger = LoggerFactory.getLogger(MyPreciseShardingAlgorithm.class);

	@Override
	public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
		logger.info("availableTargetNames : " + availableTargetNames);
		for (String tableName : availableTargetNames) {
			Date date = shardingValue.getValue();
			int month = DateUtil.month(date) + 1;
			String indexStr = tableName.substring(tableName.lastIndexOf("_") + 1);
			int index = Integer.parseInt(indexStr);
			if (index == month) {
				return tableName;
			}
		}
		throw new IllegalArgumentException();
	}

}